<?php

namespace App\Http\Controllers\Admin;

use App\Http\Filters\ReportFilter;
use App\Models\Report;
use App\Http\Requests\ReportRequest;
use App\Http\Resources\ReportResource;
use App\Models\ReportEditLog;
use App\Models\ReportUser;
use App\Models\Reportverifylog;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\ReportExport;


class ReportController extends Controller
{
    public function index(ReportFilter $filter)
    {
        $reports = Report::query()->with('postsUser')
            ->filter($filter)
            ->orderByDesc('id')
            ->paginate();
        return $this->ok(ReportResource::collection($reports));
    }

    public function create()
    {
        return $this->ok();
    }

    public function store(ReportRequest $request)
    {
        $inputs = $request->validated();
        $report = Report::create($inputs);

        return $this->created(ReportResource::make($report));
    }

    public function edit($id)
    {
        $report = Report::findOrFail($id);
        return $this->ok(ReportResource::make($report) ->for(ReportResource::FOR_EDIT)->additional($this->formData($report)));
    }

    protected function formData($report)
    {

        $reportuser = ReportUser::query()
//            ->select(['id', 'user_name','report_id'])
            ->orderByDesc('id')
            ->get();
        $reporteditlog=ReportEditLog::query()->where("report_id",$report['id'])
            ->orderByDesc('id')
            ->get();
        return compact('reportuser','reporteditlog');
    }

    public function update(ReportRequest $request, $id)
    {
        $inputs = $request->validated();
        $report = Report::findOrFail($id);
        $report->update($inputs);
        Reportverifylog::create(['report_id'=>$id,'admin_user_id'=>Auth::id(),'type'=>$inputs['type'],'content'=>isset($inputs['content']) ? $inputs['content'] :'']);
        return $this->created(ReportResource::make($report));
    }

    public function destroy(Report $report)
    {
        $report->delete();
        return $this->noContent();
    }

    public function export(Report $report)
    {
        $filters = $report->only([
            'ids',
            // ... 其他可能的过滤条件
        ]);
        return Excel::download(new ReportExport($filters), '经营报备.xlsx');
    }
}
